import { ChangeBackgroundMessage, PostMessageType } from '@/config';
import { changeImageBackground } from '@/lib/meituxiuxiu';
import { getBlobByUrl } from '@/lib/utils';
import { useSettingsStore } from '@/store';

function App() {
  const processSettings = useSettingsStore((state) => state.processSettings);

  // console.log('processSettings', processSettings);

  useEffect(() => {
    async function handlerMessage(
      message: MessageEvent<
        | ChangeBackgroundMessage
        | {
            type: PostMessageType.processSettingUpdate;
          }
      >,
    ) {
      const data = message.data;
      if (data.type === PostMessageType.changeBackground) {
        const sourceImage = data.data.sourceImage;
        const taskId = data.data.taskId;
        try {
          const resultUrl = await changeImageBackground(sourceImage, processSettings);
          let resultBlob = await getBlobByUrl(resultUrl);
          message.source!.postMessage(
            {
              type: PostMessageType.getChangedBackgroundResult,
              data: {
                errorCode: 0,
                resultUrl,
                taskId,
                resultBlob,
              },
            },
            {
              targetOrigin: 'https://www.dianxiaomi.com',
            },
          );
        } catch (error) {
          message.source!.postMessage(
            {
              type: PostMessageType.getChangedBackgroundResult,
              data: {
                errorCode: 1,
                errorMessage: `换背景时发生错误: ${(error as Error).message}`,
                taskId,
              },
            },
            {
              targetOrigin: 'https://www.dianxiaomi.com',
            },
          );
        }
      }
      if (data.type === PostMessageType.processSettingUpdate) {
        useSettingsStore.persist.rehydrate();
      }
    }
    window.addEventListener('message', handlerMessage);
    return () => {
      window.removeEventListener('message', handlerMessage);
    };
  }, [processSettings]);

  return (
    <>
      <div></div>
    </>
  );
}

export default App;
